package listeners

import (
	"blockchains-aio/conf"
	"blockchains-aio/stack"
	"blockchains-aio/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// curl -X GET http://localhost:39781/blockchainsaio/genesis_tmpl/poa2
func RegisterGenesis(router *gin.Engine) {
	rootGroup := getRootGroup(router)
	{
		rootGroup.GET("/genesis_tmpl/:consensus", getGenesisTmpl)
		rootGroup.POST("/genesis_tmpl/:consensus", makeGenesis)
	}

}

func makeGenesis(ctx *gin.Context) {
	consensus := ctx.Param("consensus")
	aNumberOfAddressesHex := ctx.PostForm("aNumberOfAddressesHex")
	if consensus == "" || consensus != "poa2" || aNumberOfAddressesHex == "" {
		ctx.JSON(http.StatusBadRequest, NewErrorMessage(Genesis, 1, "makeGenesis", fmt.Sprintf("only support poa2,bad parameters: %v", consensus)).Json())
		return
	}

	poa2GenesisTmplPath := fmt.Sprintf("%s/%s.genesis.tmpl", conf.GetStackTemplateFolder(), consensus)
	if !util.IsPathExists(poa2GenesisTmplPath) {
		ctx.JSON(http.StatusInternalServerError, NewErrorMessage(Genesis, 2, "makeGenesis", fmt.Sprintf("fail to find a template: %s", poa2GenesisTmplPath)).Json())
		return
	}

	err := stack.ParsePOAGenesisTemplate(ctx.Writer, poa2GenesisTmplPath, struct{ ANumberOfAddressesHex string }{ANumberOfAddressesHex: aNumberOfAddressesHex})
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, NewErrorMessage(Genesis, 3, "makeGenesis", fmt.Sprintf("fail to execute a template: %v", err)).Json())
		return
	}

	return
}

func getGenesisTmpl(ctx *gin.Context) {
	consensus := ctx.Param("consensus")
	genesisPath := conf.GetGenesisTemplateFolder(consensus)
	if len(genesisPath) == 0 {
		ctx.JSON(400, fmt.Sprintf("genesis.json is not available for the consensus:%s", consensus))
		return
	}
	genesis := fmt.Sprintf("%s/%s", genesisPath, "genesis.json")
	if !util.IsPathExists(genesis) {
		ctx.JSON(400, fmt.Sprintf("genesis.json is not available in the path:%s", genesis))
		return
	}

	ctx.File(genesis)
}
